#include "tr_local.h"
#include "../infLib/infLib.h"
#include <malloc.h>

static inf::BlockAlloc<srfTriangles_t, 1<<8>    srfTrianglesAllocator;

void R_InitTriSurfData( void ) {

}

void R_ShutdownTriSurfData( void ) {

    srfTrianglesAllocator.shutdown();
}

srfTriangles_t* R_AllocStaticTriSurf( void ) {
    srfTriangles_t* tris = srfTrianglesAllocator.alloc();
    inf::memory_set( tris, 0, sizeof(srfTriangles_t) );
    return tris;
}

void R_AllocStaticTriSurfVerts( srfTriangles_t *tri, int numVerts ) {
    assert( tri->verts == NULL );
    tri->verts = new DrawVert[ numVerts ];
}

void R_AllocStaticTriSurfIndexes( srfTriangles_t *tri, int numIndexes ) {
    assert( tri->indexes == NULL );
    tri->indexes = new index_t[ numIndexes ];
}

void R_FreeStaticTriSurf( srfTriangles_t* tri ) {
    if( !tri )
        return;

    if( tri->verts != NULL ) {
        delete [] tri->verts;
    }
    if( tri->indexes != NULL ) {
        delete [] tri->indexes;
    }

    srfTrianglesAllocator.free( tri );
}

void *R_StaticAlloc( int bytes ) {
	void	*buf;

    buf = malloc( bytes );

	// don't exit on failure on zero length allocations since the old code didn't
	if ( !buf && ( bytes != 0 ) ) {
		common->FatalError( "R_StaticAlloc failed on %i bytes", bytes );
	}
	return buf;
}

void *R_ClearedStaticAlloc( int bytes ) {
	void	*buf;

	buf = R_StaticAlloc( bytes );
    inf::memory_set(buf, 0, bytes);

	return buf;
}

void R_StaticFree( void *data ) {
    free( data );
}